using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;
#if  UNITY_EDITOR
using UnityEditor.Compilation;
using UnityEditor;
#endif
public class OpenFile : MonoBehaviour
{
    public List<FilterInfo> filterInfos = new List<FilterInfo>();

    [Serializable]
    public struct FilterInfo
    {
        public string Name;
        public string Filter;
    }
    void Awake()
    {
        filterInfos.Add(new FilterInfo { Name = "png", Filter = "*.png" });
        filterInfos.Add(new FilterInfo { Name = "jpg", Filter = "*.jpg" });
        // 在这里扩展,增加新的文件类型
    }

    string GetFilter()
    {
        string ret = string.Empty;
        foreach (var item in filterInfos)
        {
            ret += item.Name + "\0" + item.Filter + "\0";
        }
        return ret;
    }

    public string[] OpenFileWin(bool multiSelect)
    {
        OpenFileName ofn = new OpenFileName();

        ofn.structSize = Marshal.SizeOf(ofn);

        ofn.filter = GetFilter();

        // Create buffer for file names
        int maxCharCount = 1024;
        ofn.file = Marshal.AllocHGlobal(maxCharCount * Marshal.SystemDefaultCharSize);
        ofn.maxFile = maxCharCount;

        // Initialize buffer with NULL bytes
        for (int i = 0; i < maxCharCount * Marshal.SystemDefaultCharSize; i++)
        {
            Marshal.WriteByte(ofn.file, i, 0);
        }

        ofn.fileTitle = new string(new char[64]);

        ofn.maxFileTitle = ofn.fileTitle.Length;
        string path = Application.streamingAssetsPath;
        path = path.Replace('/', '\\');
        //默认路径  
        ofn.initialDir = path;

        ofn.title = "Open Project";

        ofn.defExt = "JPG";//显示文件的类型  
        //注意 一下项目不一定要全选 但是0x00000008项不要缺少  
        ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;//OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_NOCHANGEDIR  
        if (multiSelect)
            ofn.flags |= 0x00000200; //OFN_ALLOWMULTISELECT


        if (WindowDll.GetOpenFileName(ofn))
        {
            Debug.LogFormat("Selected file with full path: {0}", ofn.file);

            List<string> selectedFilesList = new List<string>();

            IntPtr filePointer = ofn.file;
            long pointer = (long)filePointer;
            string file = Marshal.PtrToStringAuto(ofn.file);

            // Retrieve file names
            while (file.Length > 0)
            {
                selectedFilesList.Add(file);

                pointer += file.Length * Marshal.SystemDefaultCharSize + Marshal.SystemDefaultCharSize;
                filePointer = (IntPtr)pointer;
                file = Marshal.PtrToStringAuto(filePointer);
            }

            Marshal.FreeHGlobal(ofn.file);

            if (selectedFilesList.Count == 1)
            {
                // Only one file selected with full path
                Debug.LogFormat("Selected file with full path: {0}", selectedFilesList[0]);
                return selectedFilesList.ToArray();
            }
            else
            {
                // Multiple files selected, add directory
                string[] selectedFiles = new string[selectedFilesList.Count - 1];

                for (int i = 0; i < selectedFiles.Length; i++)
                {
                    selectedFiles[i] = selectedFilesList[0] + "\\" + selectedFilesList[i + 1];
                    Debug.LogFormat("Selected file with full path: {0}", selectedFiles[i]);
                }

                return selectedFiles;
            }
        }
        else
            return null;
    }

    public string SaveFileWin()
    {
        OpenFileName ofn = new OpenFileName();
        ofn.structSize = Marshal.SizeOf(ofn);
        ofn.filter = "png\0*.png";

        // Create buffer for file names
        int maxCharCount = 1024;
        ofn.file = Marshal.AllocHGlobal(maxCharCount * Marshal.SystemDefaultCharSize);
        ofn.maxFile = maxCharCount;

        // Initialize buffer with NULL bytes
        for (int i = 0; i < maxCharCount * Marshal.SystemDefaultCharSize; i++)
        {
            Marshal.WriteByte(ofn.file, i, 0);
        }

        ofn.fileTitle = new string(new char[64]);//文件名字(带格式后缀)，格式（3-图片-花.jpg）
        ofn.maxFileTitle = ofn.fileTitle.Length;
        ofn.initialDir = Application.streamingAssetsPath.Replace('/', '\\');//默认路径
        ofn.title = "窗口标题";
        ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;

        if (WindowDll.GetSaveFileName(ofn))
        {
            Debug.LogFormat("Selected file with full path: {0}", ofn.file);

            List<string> selectedFilesList = new List<string>();

            IntPtr filePointer = ofn.file;
            long pointer = (long)filePointer;
            string file = Marshal.PtrToStringAuto(ofn.file);

            // Retrieve file names
            while (file.Length > 0)
            {
                selectedFilesList.Add(file);

                pointer += file.Length * Marshal.SystemDefaultCharSize + Marshal.SystemDefaultCharSize;
                filePointer = (IntPtr)pointer;
                file = Marshal.PtrToStringAuto(filePointer);
            }

            Marshal.FreeHGlobal(ofn.file);

            if (selectedFilesList.Count == 1)
            {
                if (selectedFilesList[0].EndsWith(".png"))
                {
                    return selectedFilesList[0];
                }

                string str = selectedFilesList[0] + ".png";
                Debug.LogFormat("save file path:{0}", str);
                return str;
            }
        }

        return null;
    }
}
